package me.jiatao.jetpack

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resumeWithException

/**
 * suspendCancellableCoroutine 使用
 */
interface HttpCallback {
    fun onSuccess(userInfo: String)
    fun onError(error: Exception)
}


fun getUserInfo(httpCallback: HttpCallback) {
    val getUserResult = true
    if (getUserResult) {
        //httpCallback.onSuccess("this is user info")
        throw Exception("Success Exception")
    } else {
        httpCallback.onError(Exception("error msg"))
    }
}

suspend fun getUserInfoWithCoroutine(): String = suspendCancellableCoroutine { cancellableContinuation ->
    getUserInfo(object : HttpCallback {
        override fun onSuccess(userInfo: String) {
            cancellableContinuation.resume(userInfo) {
                println("cancellableContinuation resume")
                it.printStackTrace()
            }
        }

        override fun onError(error: Exception) {
            cancellableContinuation.resumeWithException(error)
        }
    })
}


class MainActivity : AppCompatActivity() {

    private lateinit var flow: SharedFlow<Int>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        shareInTest()

    }

    fun shareInTest() {
        flow = (1..100000).asFlow().map {
            delay(200)
            it
        }.shareIn(
            scope = lifecycleScope,
            started = SharingStarted.WhileSubscribed(),
            replay = 10
        )
    }

    fun shareInCollect() {
        lifecycleScope.launch {
            println("flow collect before")

            flow.collect{
                println("it ---> $it")
                println(flow.replayCache.average())
            }



            println("flow collect finish")


        }
    }
//
//    fun suspendCancellableCoroutineTest() {
//        lifecycleScope.launch {
//            try {
//                val userInfo = getUserInfoWithCoroutine()
//                println("getUserInfoWithCoroutine ---> $userInfo")
//            } catch (ex: Exception) {
//
//                println("lifecycleScope.launch Exception")
//                ex.printStackTrace()
//            }
//        }
//    }

    fun onClick(view: View) {
        shareInCollect()
    }
}